package com.aaa.zs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @fileName:IllegalCharFilter
 * @description:
 * @author:zz
 * @createTime:2020/11/6 15:16
 * @version:1.0.0
 */
@Component
public class IllegalCharFilter extends ZuulFilter {

    @Value("${illegalChar}")
    private String illegalChar;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("进入了字符过滤器。。。");
        //使用zuul包中提供请求上下文类获取请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request =currentContext.getRequest();
        //获取response对象
        HttpServletResponse response = currentContext.getResponse();
        //请求：http://localhost:8888/os/a/b/order/selectAll?a=1sb2&b=2&c=3fdfd&d=4&e=fadfadsf&userName=zhangsan
        //获取所有的请求参数
        Enumeration<String> parameterNames = request.getParameterNames();
        String[] charArray = illegalChar.split(",");
        System.out.println(charArray+".........");
        //[a,b,c,d,e,userName]
        //判断有没有更多元素
        while(parameterNames.hasMoreElements()){
            //第一次a ,第二次b,第三次c....
            String paramName = parameterNames.nextElement();
            //根据名称获取参数值  第一次 1sb2  第二次2  第三次3fdfd ....
            String paramValue = request.getParameter(paramName);
            for (String illegalC : charArray) {
                if(paramValue.contains(illegalC)){
                    currentContext.setSendZuulResponse(false);
                    response.setCharacterEncoding("utf-8");
                    try {
                        response.sendError(HttpStatus.SC_FORBIDDEN,
                                "你的请求中含有非法参数，不允许访问我的网站");
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
